﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Commands.PivotGrid
{
    using Galaktika.BI.Extensibility.Dom.Mdx;
    using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
    using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.Services;
    using Galaktika.BI.Silverlight.Controls;
    using Galaktika.BI.Extensibility.Dom.Mdx.Compiler;
    using System.Text;
    using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;
    using Galaktika.BI.Extensibility.Utils.Serialization;
    using Galaktika.BI.Runtime.Services;
    using Ranet.Olap.Core.Data;
    using Ranet.AgOlap.Controls.PivotGrid.ClientServer;
    using Ranet.AgOlap.Controls.PivotGrid;

    public class DrillDownCommand : ServerCommand
    {
        public DrillDownCommand(InvokeSchema invoker)
            : base(Galaktika.BI.Silverlight.Commands.CommandId.DrillDownCommandId)
        {
            this.ContextId = invoker[KnownInvokeArgs.ContextId];
            this.DataSourceId = invoker[KnownInvokeArgs.DataSourceId];
            this.Args = invoker[KnownInvokeArgs.MemberAction];
        }

        public string ContextId { get; private set; }
        public string DataSourceId { get; private set; }
        public string Args { get; private set; }

        private IBindingContext Context
        {
            get
            {
                return DataBinder.Current.GetContext(this.ContextId);
            }
        }

        private OlapDataManager DataManager
        {
            get
            {
                IBindingManager bindingMgr = DataBinder.Current.GetBindingManager(this.ContextId, this.DataSourceId);
                if (bindingMgr != null)
                {
                    return bindingMgr.DataManager as OlapDataManager;
                }

                return null;
            }
        }

        public override InvokeResultSchema Invoke()
        {
            InvokeResultSchema res = new InvokeResultSchema(base.Id);

            DataBinder binder = DataBinder.Current;

            PerformMemberActionArgs args = XmlUtility.XmlStr2Obj <PerformMemberActionArgs>(this.Args);
            CellSetData csd = this.PerformMemberAction(args);

            res.Content = XmlUtility.Obj2XmlStr(csd, Common.Namespace);
            res.ContentType = KnownContentTypes.MultidimData;
                
            return res;
        }


        private CellSetData PerformMemberAction(PerformMemberActionArgs args)
        {
            if (DataManager != null)
            {
                DataManager.Context = this.Context;
                return DataManager.PerformMemberAction(args);
            }
            return null;
        }
   }
}
